package com.dropdb.demo.controller.wx;

import com.dropdb.demo.bean.Address;
import com.dropdb.demo.bean.User;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.bean.vo.DetailAddressVO;
import com.dropdb.demo.bean.vo.WxAddressVO;
import com.dropdb.demo.service.WxAddressService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:cheyanjun
 * @date:2020/06/30 23:55
 */
@RestController
@RequestMapping("wx/address")
public class WxAddressController {

    @Autowired
    WxAddressService wxAddressService;

    /**
     * 根据用户信息获得用户的地址列表
     * @return AddressList
     */
    @GetMapping("list")
    public BaseRespVO getAddressList(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        int userId=user.getId();
        List<WxAddressVO> data=wxAddressService.getAddressList(userId);
        return BaseRespVO.ok(data);
    }

    /**
     * 获取详细地址
     * @param id
     * @return 详细地址
     */
    @GetMapping("detail")
    public BaseRespVO getAddressDetail(int id){
        DetailAddressVO data=wxAddressService.getAddressDetail(id);
        return BaseRespVO.ok(data);
    }

    /**
     * 保存地址修改或新建地址
     * @param address
     * @return
     */
    @PostMapping("save")
    public BaseRespVO saveAddress(@RequestBody Address address){
        //获得登录信息中用户id
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        int userId=user.getId();
        //将用户id放入从前台传入的address数据中，便于后面进行数据库的修改
        address.setUserId(userId);
        //判断当前传入修改的地址address是否设置为默认地址：
        // 是，则需更改数据库该用户的其他地址记录的默认设置为false；
        // 否，则不需要改变
        if(address.getIsDefault()==true){
            wxAddressService.updateIsDefault(address.getUserId());
        }
        //若address的id不为0说明address表已有该地址，只需要保存地址修改，就是更新数据
        if(address.getId()!=0){
            wxAddressService.saveAddress(address);
            return BaseRespVO.ok(address.getId());
        }else { //若address的id为0说明address表无该地址，则需要保存新建的地址，也就是插入数据
            int id =wxAddressService.addAddress(address);
            return BaseRespVO.ok(id);
        }
    }

    /**
     * 删除地址
     * @param map
     * @return
     */
    @PostMapping("delete")
    public BaseRespVO deleteAddress(@RequestBody Map map){
        Integer id = (Integer) map.get("id");
        wxAddressService.deleteAddress(id);
        return BaseRespVO.ok();
    }
}
